package lambdasinaction.chap3;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

/**
 * Created by ThinkPad on 2017/8/16.
 */
public class Sorting {

    public static void main(String... args) {
        List<Apple> inventory = Arrays.asList(new Apple(80,"green"),
                new Apple(155,"green"),
                new Apple(120,"red"));
//        1.传递代码
        inventory.sort(new AppleComparator());
        System.out.println(inventory);
//        2.使用匿名类
        inventory.sort(new Comparator<Apple>() {
            @Override
            public int compare(Apple o1, Apple o2) {
                return o1.getWeight().compareTo(o2.getWeight());
            }
        });
        System.out.println(inventory);
//        3.使用Lambda
        inventory.sort((a1,a2) -> a1.getWeight().compareTo(a2.getWeight()));
//        Comparator接口有个静态辅助方法comparing,
        inventory.sort(Comparator.comparing((a) -> a.getWeight()));
        System.out.println(inventory);
//        4.使用方法引用
//        代码读起来和问题描述差不多了:"对库存进行排序,比较苹果的重量"
        inventory.sort(Comparator.comparing(Apple::getWeight));
        System.out.println(inventory);
//        比较器复合
        inventory.sort(Comparator.comparing(Apple::getWeight)
                .reversed()
                .thenComparing(Apple::getColor));
    }

    public static class Apple {
        private Integer weight;
        private String color;

        public Apple(Integer weight, String color) {
            this.weight = weight;
            this.color = color;
        }

        public Integer getWeight() {
            return weight;
        }

        public void setWeight(Integer weight) {
            this.weight = weight;
        }

        public String getColor() {
            return color;
        }

        public void setColor(String color) {
            this.color = color;
        }

        @Override
        public String toString() {
            return "Apple{" +
                    "color='" + color + '\'' +
                    ", weight=" + weight +
                    '}';
        }
    }

    static class AppleComparator implements Comparator<Apple> {

        @Override
        public int compare(Apple o1, Apple o2) {
            return o1.getWeight().compareTo(o2.getWeight());
        }
    }
}
